package com.wstuo.common.tools.service;

import java.io.File;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.wstuo.common.tools.dto.FileUploadDTO;
import com.wstuo.common.tools.util.ToolsUtils;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.security.utils.AppContext;

public class FileUpload implements IFileUpload {
	
	final static Logger LOGGER = Logger.getLogger(FileUpload.class);
	@Autowired
	private AppContext appctx;
	/**
	 * 文件上传
	 */
	public FileUploadDTO fileUpload(File myFile,String fileName,String imageFileName,String imgSize,String myFileName){
		FileUploadDTO dto = new FileUploadDTO();
		String IMAGEPATH = AppConfigUtils.getInstance()
		.getConfigPathByTenantId("imagePath", "/images",appctx.getCurrentTenantId());
		String JASPERPATH = AppConfigUtils.getInstance()
		 .getConfigPathByTenantId("jasperPathRoot", "/jasper",appctx.getCurrentTenantId());
		try {
			if (imgSize != null && myFile.length() > 150000) {
				dto.setImageFileName("Image is too big");
				dto.setResult("ERROR");
			}else{
				String fileUrl = "";
				if (imageFileName != null) {
					fileUrl = JASPERPATH + "/" + imageFileName;
					myFile = new File((IMAGEPATH + "/" + myFileName).replace("WEB-INF/classes/", ""));
				} else {
					fileUrl = IMAGEPATH + "/" + new Date().getTime()+ getExtention(fileName);
					imageFileName = new Date().getTime() + getExtention(fileName);
				}
				fileUrl = fileUrl.replace("WEB-INF/classes/", "");
				File imageFile = new File(fileUrl);
				ToolsUtils.copy(myFile, imageFile);
				dto.setImageFileName(imageFileName);
				dto.setResult("success");
			}
		} catch (Exception ex) {
			LOGGER.error(ex.getMessage());
		}
		return dto;
	}
	
	/**
	 * 获取文件类型.
	 * 
	 * @param String
	 *            文件名
	 * @return String 文件类型
	 */
	private static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}
}
